/**
 * 
 */
package com.edu.lawdoc.generator.field.component.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.edu.lawdoc.generator.field.JavaCodeGenerator;
import com.edu.lawdoc.generator.field.component.JavaCodeTemplateRender;
import com.edu.lawdoc.generator.field.kits.FileWriter;
import com.edu.lawdoc.generator.field.meta.ColumnMeta;
import com.edu.lawdoc.generator.field.meta.MetaData;
import com.edu.lawdoc.generator.field.meta.TableMeta;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;


/**
 * @author huxiao
 *
 */
public class ColumnConstTemplateRender implements JavaCodeTemplateRender {
	private String outputPackage = null;
	private String mavenMainJavaPath = null;
	
	public ColumnConstTemplateRender(String mavenMainJavaPath, String outputPackage) {
		this.mavenMainJavaPath = mavenMainJavaPath;
		this.outputPackage = outputPackage;
	}

	/**
	 * 生成Column字段的静态引用
	 */
	public void render(Engine engine, MetaData metaData) {
		List<Map<String, Object>> targetList = new ArrayList<Map<String, Object>>();
		
		Map<String, TableMeta> tablesWithColumnMetaMapping = metaData.getTablesWithColumnMetaMapping();
		Iterator<Map.Entry<String, TableMeta>> it = tablesWithColumnMetaMapping.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, TableMeta> entry = it.next();

			/**
			 * 得到表名，并转为大写
			 */
			String tName = entry.getKey();
			String upperTableName = tName.toUpperCase();

			List<Map<String, String>> targetColumns = new ArrayList<Map<String, String>>();

			TableMeta oTableMeta = entry.getValue();
			List<ColumnMeta> columnMetaList = oTableMeta.getColumnMetaList();
			for (ColumnMeta oColumnMeta : columnMetaList) {
				/**
				 * 得到列名，并获得列的java类型
				 */
				String columnName = oColumnMeta.getName();
				String originClazz = oColumnMeta.getOriginClass();

				Map<String, String> targetM = new HashMap<String, String>();
				targetM.put("upper", columnName.toUpperCase());
				targetM.put("name", columnName);
				targetM.put("origin_clazz", originClazz);
				targetColumns.add(targetM);
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("table_name__upper", upperTableName);
			map.put("table_name", tName);
			map.put("column_list", targetColumns);
			targetList.add(map);
		}

		Kv cond = Kv.by("list", targetList)
				.set("package", outputPackage);

		String templatePath = ColumnConstTemplateRender.class.getResource("").getPath()
				+ "../../template/Template__Column.enjoy";
		String template = engine.getTemplate(templatePath).renderToString(cond);

		FileWriter.write(JavaCodeGenerator.toPath(mavenMainJavaPath, outputPackage), "Column", "java", template);
	}

}
